package io.qifan.desktop.client.views.index;

import io.qifan.desktop.client.event.Events;
import io.qifan.desktop.client.registry.ViewRegistry;
import io.qifan.desktop.client.views.BaseController;
import io.qifan.desktop.client.views.connect.ConnectController;
import io.qifan.desktop.client.views.device.DeviceController;
import io.qifan.desktop.client.views.login.LoginController;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.ResourceBundle;

@Component
@Slf4j
@Scope
public class IndexController implements BaseController, Initializable {
    public VBox leftPane;
    public VBox rightPanel;
    public ImageView avatarImage;
    public Label username;
    public Button loginBtn;
    public Button quitBtn;
    public ListView<String> menus;

    public Map<String, Class<? extends BaseController>> menuToPanelMap;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        menuToPanelMap = Map.of("远程协助", ConnectController.class, "设备列表", DeviceController.class);
        avatarImage.setImage(new Image("/static/logo.jpg", 60, 60, true, true));
        menus.setItems(FXCollections.observableList(new ArrayList<>(menuToPanelMap.keySet())));
        menus.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    log.info("当前选中菜单：{}", newValue);
                    switchPanel(menuToPanelMap.get(newValue));
                });

    }

    public void switchPanel(Class<? extends BaseController> controller) {
        rightPanel.getChildren().setAll((Node) ViewRegistry.get(controller));
    }

    public void handleLogin() {
        switchPanel(LoginController.class);
    }


    public void handleQuit(ActionEvent actionEvent) {
        loginBtn.setVisible(true);
        username.setVisible(false);
        quitBtn.setVisible(false);
    }

    @EventListener(Events.LoginSuccessEvent.class)
    public void handleLoginSuccessForPanelSwitch() {
        log.info("切换到连接界面");
        switchPanel(ConnectController.class);
        loginBtn.setVisible(false);
        username.setVisible(true);
        quitBtn.setVisible(true);
    }
}
